package org.hoyi.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;

import org.hoyi.DB.ctrl.Console;

public class ValiCode
{

	public static int GenerateCode()
	{

		int max = 999999;
		int min = 100000;
		Random random = new Random();

		int s = random.nextInt(max) % (max - min + 1) + min;

//		System.out.println("valicode:" + s);
		return s;
	}

	/**
	 * 发送短信
	 * 
	 * @param phone
	 * @param code
	 */
	public static String sendCode(String phone, int code, String _key)
	{
		String url = "http://v.juhe.cn/sms/send";// url为请求的api接口地址
		String tpl_value = "#code#=" + code;
		String key = "?mobile=" + phone + "&tpl_id=2912&tpl_value=" + URLEncoder.encode(tpl_value) + "&key=" + _key;// 申请的对应key
		String urlAll = new StringBuffer(url).append(key).toString();
		String charset = "UTF-8";
		String jsonResult = get(urlAll, charset);// 得到JSON字符串
		return jsonResult;
	}

	/**
	 * @param urlAll
	 *            :请求接口
	 * @param charset
	 *            :字符编码
	 * @return 返回json结果
	 */
	public static String get(String urlAll, String charset)
	{
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";// 模拟浏览器
		try
		{
			URL url = new URL(urlAll);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setReadTimeout(30000);
			connection.setConnectTimeout(30000);
			connection.setRequestProperty("User-agent", userAgent);
			connection.connect();
			InputStream is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, charset));
			String strRead = null;
			while ((strRead = reader.readLine()) != null)
			{
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close();
			result = sbf.toString();

		}
		catch (Exception e)
		{
			Console.Error(e);
		}
		return result;
	}
}
